package com.jule.teenpatti.mail.network.protocol;

import com.google.protobuf.MessageLite;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by lyb on 2018/6/19
 */
@Slf4j
public class ClientAck {

    protected int functionId;
    protected final ClientHeader header;
    protected MessageLite body;

    public boolean encode(final ByteBuf buffer) {
        try {
            buffer.writeInt(functionId);
            buffer.writeInt(header.gameId);
            buffer.writeInt(header.gameServerId);
            buffer.writeInt(header.isAsync ? 1 : 0);
            buffer.writeInt(header.reqNum);
            buffer.writeLong(header.channelId);

            if (body != null) {
                buffer.writeBytes(body.toByteArray());
                log.debug(String.format("send function-> 0x%02X(%d)", functionId, functionId & 0x00FFFFFF) + ",content:" + body.toString());
            }
            return true;
        } catch (Exception e) {
            log.error("encode", e);
            ReferenceCountUtil.release(buffer);
            return false;
        }
    }

    /**
     * @param messageLite
     */
    public ClientAck(MessageLite messageLite, ClientHeader header) {
        this.body = messageLite;
        this.header = header;
    }

    public void setFunctionId(int functionId) {
        this.functionId = functionId;
    }
}
